﻿using System;
using TeamRobin.BattleCity.Core.Levels;
using TeamRobin.BattleCity.Core.ScreenText;
using TeamRobin.BattleCity.Core.Utils;

namespace TeamRobin.BattleCity.Core
{
	internal abstract class Game
	{
		private static int _currentLevel = 1;
		private static Level level;
		public static bool IsGameLevelRunning;

		protected static void Start()
		{
			GameScreen.BattleCity();
			Console.Clear();
			NextLevel();
			Border.DrawBorder();
			Play();
		}

		public static void NextLevel()
		{
			if (level != null)
			{
				Console.Clear();
			}
			GameScreen.SetLevelScreen();

			var nextLevel = (LevelType)Enum.Parse(typeof(LevelType),
				_currentLevel > 9 ?
				"_" + _currentLevel :
				"_0" + _currentLevel);

			IsGameLevelRunning = true;
			level = new Level(nextLevel);
			level.Write();
			ScoreScreen.SideScreen(level.Player1, level.Type, level.AITanks);
		}

		public static void LevelEnd()
		{
			foreach (var entity in level.Entities)
			{
				entity.IsDestroyed = true;
			}
			level = null;
		}

		public static void Continue(bool success)
		{
			if (success)
			{
				_currentLevel++;
				NextLevel();
			}
			else
			{
				Start();
			}
		}

		private static void Play()
		{
			while (true)
			{
				if (Console.KeyAvailable)
				{
					ConsoleKeyInfo keyPressed = Console.ReadKey(true);
					while (Console.KeyAvailable) { Console.ReadKey(true); }
					switch (keyPressed.Key)
					{
						case ConsoleKey.DownArrow:

						case ConsoleKey.LeftArrow:

						case ConsoleKey.RightArrow:

						case ConsoleKey.UpArrow:
							if (level != null)
								level.Player1.Move(keyPressed.Key);
							break;

						case ConsoleKey.Spacebar:
							if (level != null)
							{
								level.Player1.Fire();
								Sounds.FireWeapon();
							}
							break;

						default:
							break;
					}
				}
			}
		}
	}
}